package com.devilwwj.http.callback;

import android.util.JsonReader;
import android.util.Log;

import com.devilwwj.http.core.AbstractDataCallback;
import com.devilwwj.http.entities.IEntity;
import com.devilwwj.http.exception.HttpException;

import java.io.FileReader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * Created by devilwwj on 15/7/27.
 */
public abstract class JSONArrayReaderCallback<T extends IEntity> extends AbstractDataCallback<ArrayList<T>> {

    @Override
    public ArrayList<T> bindData(String content) throws HttpException {
        try {
            Log.e("devilwwj", "JsonArrayReaderCallback bindData:" + content);

            // 获取类型
            Type type = ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            ArrayList<T> ts = new ArrayList<T>();
            T t;

            FileReader in = new FileReader(content);
            JsonReader reader = new JsonReader(in);
            String node;
            reader.beginObject();
            while(reader.hasNext()) {
                node = reader.nextName();
                if ("data".equalsIgnoreCase(node)) {
                    reader.beginArray();
                    while(reader.hasNext()) {
                        t = ((Class<T>)type).newInstance();
                        t.readFromJson(reader);
                        ts.add(t);
                    }
                    reader.endArray();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
            return ts;
        } catch (Exception e) {
           throw new HttpException(HttpException.ErrorType.JSON, e.getMessage());
        }
    }
}
